package cn.js.ccit.servlet;

import cn.js.ccit.entity.Branch;
import cn.js.ccit.service.BranchService;
import cn.js.ccit.service.impl.BranchServiceImpl;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/branchServlet")
public class BranchServlet extends HttpServlet {

    BranchService branchService = new BranchServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String branchIdStr = req.getParameter("branchId");

        if(StringUtils.isNullOrEmpty(branchIdStr)){
            //查询机构信息列表
            Branch branch = new Branch();
            List<Branch> branchList = branchService.getBranchBy(branch);
            req.setAttribute("branchList", branchList);
        }else{
            //根据ID查询机构信息
            Integer branchId = Integer.parseInt(branchIdStr);
            Branch branch = branchService.getBranchById(branchId);
            req.setAttribute("branch", branch);
            req.getRequestDispatcher("addBranch.jsp").forward(req, resp);
        }

    }

    /**
     * 添加新机构
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        // 获取参数
        String branchName = req.getParameter("branchName");
        String remark = req.getParameter("remark");

        // 查看该机构是否存在
        Branch branch = new Branch();
        branch.setBranchName(branchName);
        branch.setRemark(remark);
        if(branchService.isExist(branch)){
            // 机构信息已存在
        }else {
            // 添加机构信息
            branchService.addBranch(branch);
        }
        resp.sendRedirect("branchList.jsp");

    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String branchIdStr = req.getParameter("branchId");

        if(!StringUtils.isNullOrEmpty(branchIdStr)){
            //根据ID删除机构信息
            Integer branchId = Integer.parseInt(branchIdStr);
            branchService.deleteBranchById(branchId);
        }
        resp.sendRedirect("branchList.jsp");
    }
}
